/*
 * @Description: 
 * @Author: fhw
 * @Date: 2022-12-06 15:26:51
 */
import { Injectable, UseFilters } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { HttpExceptionFilter } from 'src/http-exception.filter';
import { getPagination, throwHttp } from 'src/utlis';
import { Repository } from 'typeorm';
import { GetUserChatRecord } from './dto/chat-record.dto';
import { GetGroupChatRecord } from './dto/group-record.dto';
import { GroupChatRecord } from './entities/group-chat-record.entity';
import { UserChatRecord } from './entities/user-chat-record.entity';

@Injectable()
export class ChatRecordService {
  constructor(
    @InjectRepository(UserChatRecord)
    private UserChatRecordRepository: Repository<UserChatRecord>,
    @InjectRepository(GroupChatRecord)
    private groupChatRecordRepository: Repository<GroupChatRecord>,
  ) { }
  @UseFilters(new HttpExceptionFilter())
  async getUserChatRecord(params: GetUserChatRecord) {
    try {
      const { userId, to_userId } = params
      const { pageSize, pageNum } = getPagination({ pageSize: params.pageSize, pageNum: params.pageNum })
      const options = {
        where: [
          {
            userId: Number(userId),
            to_userId: Number(to_userId),
          },
          {
            userId: Number(to_userId),
            to_userId: Number(userId),
          },
        ],
        cache: true,
        order: { createDate: 'desc' },
        skip: null,
        take: pageSize,
      } as any
      if (params.pageNum) {
        options.skip = pageNum * pageSize
      }
      const [data, total] = await this.UserChatRecordRepository.findAndCount(options)
      const userChatRecordList = data
      return {
        data: userChatRecordList.sort((a, b) => (new Date(a.createDate) as any) - (new Date(b.createDate) as any)),
        total,
        pageSize,
        pageNum:  pageNum + 1,
      }
    } catch (error) {
      throwHttp(error.message)
    }
  }
  /**
   * 
   * @param {Object} params 
   */
  @UseFilters(new HttpExceptionFilter())
  async getGroupChatRecord(params: GetGroupChatRecord) {
    try {
      const { group_id } = params
      const { pageSize, pageNum } = getPagination({ pageSize: params.pageSize, pageNum: params.pageNum })
      const options = {
        where: { group_id },
        cache: true,
        order: { createDate: 'desc' },
        skip: null,
        take: pageSize,
      } as any
      if (params.pageNum) {
        options.skip = pageNum * pageSize
      }
      const [data, total] = await this.groupChatRecordRepository.findAndCount(options)
      return {
        data: data.sort((a, b) => (new Date(a.createDate) as any) - (new Date(b.createDate) as any)),
        total,
        pageSize,
        pageNum: pageNum + 1,
      }
    } catch (error) {
      throwHttp(error.message)
    }
  }
}
